#include "IOServer.h"

void AnalogInput::getValue()
{
    char buf[64];
    snprintf(buf, 64, "data:%02d", value);
    webGuiServer->send(200, "text/plain", buf);
}

void AnalogInput::init()
{
    pinMode(pin, INPUT);
    webGuiServer->on(getValueUri.c_str(),[&]{getValue();});
}

void AnalogInput::update()
{
    if (mode != WEB_IO_LOGIC)
    {
        value = m * analogRead(pin) + b;
    }
}

void AnalogInput::createWidget(std::string name, int interval)
{
    loopFunc = "\
        setInterval(" + name + "Loop, " + std::to_string(interval) + ");";
    
    HTML = "\
        <div style=\"border:1px solid black; width:100px; float:left; margin-left: 30px;\">\
            <p id=\"" + name + "_value\">" + name + ": 0</p>\
        </div>";
    
    JS = "\
        function " + name + "Loop() {\
            var response = get_" + name + "();\
            var value = response.split(\":\")[1].trim();\
            document.getElementById(\"" + name + "_value\").innerHTML =" + "\"" + name + ": \" + value;\
        }\
        function get_" + name + "() {\
            var xmlHttp = new XMLHttpRequest();\
            xmlHttp.open( \"GET\", \"/get_" + name + "\", false );\
            xmlHttp.send( null );\
            return xmlHttp.responseText;\
        }";
}

AnalogInput::AnalogInput(std::string name, int interval) 
{
    ioType = AI;
    setUri(name);
    mode = WEB_IO_LOGIC;
    createWidget(name, interval);
}

AnalogInput::AnalogInput(std::string name, uint8_t pin, int interval) 
{
    ioType = AI;
    setUri(name);
    this->pin = pin;
    createWidget(name, interval);
}
